#include <iostream>
#include <sstream>
#include <SFML/Graphics/RenderWindow.hpp>
#include <nice2d/macros.h>
#include <nice2d/scene.h>
#include <nice2d/sprite.h>
#include <nice2d/background.h>
#include <nice2d/input.h>
#include <nice2d/actions/movementaction.h>

class UnitScene : public Scene, public Input
{
public:
    void onInitialed()override
    {
        setInputMessageTarget(shared_from_this());

        setBackground(Background::create(sf::Color::Green));
        setSceneBox({0.0f, 0.0f, 800.0f, 600.0f});

        sprite = std::make_shared<Sprite>();
        sprite->setSize(64.0f, 64.0f);
        sprite->setBackgroundColor(sf::Color::Transparent);
        sprite->setSpriteColor(sf::Color::Red);
        sprite->addSpriteImage("./../data/icon/nato/units/infantry.png");
        sprite->addSpriteImage("./../data/icon/nato/sizes/division.png");
        sprite->setCenter(400.0f, 300.0f);
        addChild(sprite);

        auto text = createToastText();
        text->setText("moving sprite by Left or Right Key!");
        addChild(text);
    }

    void onKeyPressed(const sf::Event::KeyEvent &event) override
    {
        auto position = sprite->getPosition();
        if (event.code == sf::Keyboard::Left) {
            if (position.x < 15.0f)
                return;

            auto action = std::make_shared<MovementAction>(0.6f);
            action->setTargetPosition({-15.0f, 0.0f});
            sprite->runAction(action);
        } else if (event.code == sf::Keyboard::Right) {
            if (800.0f - position.x - 64.0f  < 15.0f)
                return;

            auto action = std::make_shared<MovementAction>(0.6f);
            action->setTargetPosition({15.0f, 0.0f});
            sprite->runAction(action);
        }
    }
private:
    std::shared_ptr<Sprite> sprite;
};

DECLARE_MAIN_FUNCTION_WITH_SCENE(800, 600, "unit07", UnitScene)
